<?php

namespace common\components;

/**
 * @author  shuang
 * @date    2016-11-3 15:46:17
 * @version V1.0
 * @desc    
 */
use yii\base\Event;
use common\components\MTools;
use Yii;
use yii\helpers\ArrayHelper;
use frontendm\models\WB_Task;
use frontendm\models\WB_UserTaskOperate;
use frontendm\models\WB_UserProfile;
use frontendm\models\WB_UserAccountHy;
use frontendm\models\WB_UserPayRecordHy;
use frontendm\models\WB_TaskTop;
use frontendm\models\WB_TaskReflesh;
use frontendm\models\WB_UserRebateRecord;
use yii\web\UploadedFile;
use frontendm\models\WB_TaskReport;

class OperateEvent extends Event {

    public $userid;  //操作任务用户编号
    public $taskid; //任务编号
    private $_task; //任务对象

    /*
     * 数据模型错误提示
     * @params $array ["errors"=>[]]
     */

    private function errorMessage($errors) {
        foreach ($errors as $item) {
            $this->sender->message = $item[0];
            break;
        }
    }

    /*
     * 操作成功
     */

    private function operateSuccess() {
        $this->sender->flag = true;
        $this->sender->message = ArrayHelper::getValue($this->data, "operateMsg") . "：操作成功";
    }

    /*
     * 检测任务区域
     * @params $areaname
     */

    protected function checkAreaTask($areaname) {
        if ($areaname && $areaname != "全部") {
            if ($areaname != Yii::$app->user->identity->login_area) {
                $this->sender->message = "对不起，您登陆地区不在任务范围";
                return false;
            }
        }
    }

    /*
     * 获取任务对象
     */

    protected function getTask() {
        if ($this->_task === null) {
            $this->_task = WB_Task::findOne($this->taskid);
        }
        return $this->_task;
    }

    /*
     * 获取用户操作该任务量
     */

    protected function getCurrentOperateCount() {
        return WB_UserTaskOperate::find()
                        ->where("userid=:userid and taskid=:taskid", [":userid" => $this->userid, ":taskid" => $this->taskid])
                        ->count();
    }

    /*
     * 已完成任务量
     */

    protected function getAllOperateCount() {
        return WB_UserTaskOperate::find()
                        ->where("userid=:userid and status=:status", [":userid" => $this->userid, ":status" => 1])
                        ->count();
    }

    /*
     * 添加用户操作
     */

    protected function addOperateTask() {
        $result = WB_UserTaskOperate::addOperateRecord($this->userid, $this->taskid);
        if (is_array($result)) {
            $this->errorMessage(ArrayHelper::getValue($result, "errors"));
            return false;
        }
        $this->sender->operateid = $result;
    }

    /*
     * 创建、更新账户
     * @params $amount
     * @params $offline_amount
     */

    protected function updateAmount($amount = 0, $offline_amount = 0) {
        $uesraccount = WB_UserAccountHy::find()->where("userid=" . ArrayHelper::getValue($this->data, "userid"))->one();
        if ($uesraccount) {
            $uesraccount->amount = $uesraccount->amount + $amount + $offline_amount;
            $uesraccount->offline_amount = $uesraccount->offline_amount + $offline_amount;
            return $uesraccount->save();
        } else {
            $useraccount = new WB_UserAccountHy();
            $useraccount->userid = ArrayHelper::getValue($this->data, "userid");
            $useraccount->amount = 0;
            $useraccount->offline_amount = 0;
            return $useraccount->save();
        }
    }

    /*
     * 监测置顶任务
     */

    protected function monitorTop() {
        $time = time();
        WB_TaskTop::deleteAll("end_at <=" . $time);
    }

    /*
     * 检查刷新任务
     */

    protected function monitorReflash() {
        $reflash = WB_TaskReflesh::find()->all();
        if (!empty($reflash)) {
            $trans = Yii::$app->db->beginTransaction();
            try {
                foreach ($reflash as $item) {
                    if ($item->reflash_count > $item->ref_pass) {
                        //更新任务刷新时间
                        $task = WB_Task::findOne($item->taskid);
                        //判断是否到了刷新时间
                        if ($task->reflash_at - time() >= 3600) {
                            $task->reflash_at = time();
                            $task->update();
                            //更新当前刷新次数
                            $item->ref_pass = $item->ref_pass + 1;
                            $item->update();
                        }
                    } else {
                        $item->delete();
                    }
                }
                $trans->commit();
            } catch (Exception $ex) {
                $trans->rollBack();
                throw new \yii\web\NotFoundHttpException;
            }
        }
    }

    /*
     * 检测任务完成总量
     * @params $taskid
     */

    protected function checkTaskcomcount($taskid) {
        $this->taskid = $taskid;
        $count = WB_UserTaskOperate::find()->where("taskid=:taskid and status=:status", [":taskid" => $taskid, ":status" => 1])->count();
        if ($this->getTask()->number == $count) {
            $this->getTask()->status = 70;
            if ($this->getTask()->update()) {
                //检测是否置顶
                WB_TaskTop::deleteAll("taskid=$taskid");
            }
            return true;
        }
        return true;
    }

    /*
     * 推荐人佣金返回
     * @params $userid
     */

    protected function referRebate($userid, $amount) {
        return TRUE;
        $fuser = WB_UserProfile::find()->where("userid=:userid", [":userid" => $userid])->one();
        if ($fuser->invite_code) {
            $tuser = \common\models\User::find()->where("my_code=:invite_code", [":invite_code" => $fuser->invite_code])->one();
            if ($tuser instanceof \common\models\User) {
                $rebateRecord = WB_UserRebateRecord::find()->where("fuserid=:fuserid and tuserid=:tuserid and rebate_type=2", [":fuserid" => $fuser->userid, ":tuserid" => $tuser->id])->one();
                if (!$rebateRecord) {
                    WB_UserPayRecordHy::createRecord($tuser->id, 0.3, 1, 1, $fuser->username . "做任务返还佣金￥0.3");
                    $model = new WB_UserRebateRecord();
                    $model->fuserid = $fuser->userid;
                    $model->fusername = $fuser->username;
                    $model->tuserid = $tuser->id;
                    $model->tusername = $tuser->username;
                    $model->rebate_amount = 0.3;
                    $model->amount = $amount;
                    $model->rebate_type = 2;
                    if ($model->save()) {
                        if ($tuser->wallet) {
                            $tuser->wallet->offline_amount = $tuser->wallet->offline_amount + 0.3;
                            $tuser->wallet->can_drawal_amount = $tuser->wallet->can_drawal_amount + 0.3;
                            return $tuser->wallet->save();
                        } else {
                            $useraccount = new \frontendm\models\WB_UserAccountHy();
                            $useraccount->userid = $tuser->id;
                            $useraccount->offline_amount = 0.3;
                            $useraccount->can_drawal_amount = 0.3;
                            $useraccount->yet_drawal_amount = 0;
                            return $useraccount->save();
                        }
                    }
                }
            }
        }
        return true;
    }

    /*
     * 开始任务
     */

    public function openTask() {
        $tasknum = ArrayHelper::getValue($this->data, "tasknum");
        if (!$this->getTask() instanceof WB_Task) {
            throw new \yii\web\NotFoundHttpException();
        }
        if ($tasknum <= 0) {
            $this->sender->message = "对不起，当前任务已经发放完了！";
            return false;
        }
        //判断区域
        if ($this->checkAreaTask($this->getTask()->areaname) === false) {
            return false;
        }
        if ($this->getCurrentOperateCount() > 0) {
            if ($this->getTask()->single_meet <= $this->getCurrentOperateCount()) {
                $this->sender->message = "您已参加过此任务，请不要重复操作任务！";
                return false;
            }
            if ($this->getAllOperateCount() < MTools::getYiiParams("more_meet_limit")) {
                $this->sender->message = "级别不够，完成100票合格任务可接";
                return false;
            }
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($this->addOperateTask() !== false) {
                $trans->commit();
                $this->operateSuccess();
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 隐藏任务
     */

    public function hideTask() {
        $operateModel = WB_UserTaskOperate::findOne(ArrayHelper::getValue($this->data, "operateid"));
        if (!$operateModel instanceof WB_UserTaskOperate) {
            $this->sender->message = "获取任务延迟，请稍后重试";
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            $hidden = \frontendm\models\WB_TaskHidden::find()->where("userid=:userid and taskid=:taskid", [":userid" => $this->userid, ":taskid" => $operateModel->taskid])->one();
            if ($hidden instanceof \frontendm\models\WB_TaskHidden) {
                $this->sender->message = "您已隐藏了此任务，请不要重复隐藏。";
                return false;
            } else {
                $taskhidden = new \frontendm\models\WB_TaskHidden();
                $taskhidden->hidden_time = 1;
                $taskhidden->userid = $this->userid;
                $taskhidden->taskid = $operateModel->taskid;
                $result = MTools::saveModel($taskhidden);
                if ($result !== true) {
                    $this->errorMessage(ArrayHelper::getValue($result, "errors"));
                    return false;
                } else {
                    $trans->commit();
                    $this->operateSuccess();
                }
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 报告任务过期 reportTask
     */

    public function reportTask() {
        $operateModel = WB_UserTaskOperate::findOne(ArrayHelper::getValue($this->data, "operateid"));
        if (!$operateModel instanceof WB_UserTaskOperate) {
            $this->sender->message = "获取任务延迟，请稍后重试";
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            $taskreport = new WB_TaskReport();
            $taskreport->taskid = $operateModel->taskid;
            $taskreport->report_userid = Yii::$app->user->id;
            $result = MTools::saveModel($taskreport);
            if ($result !== true) {
                $this->errorMessage(ArrayHelper::getValue($result, "errors"));
                return false;
            } else {
                $trans->commit();
                $this->operateSuccess();
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 公众号中直接提交任务图片
     */

    public function completeTasks($img = array(), $operateid = null, $taskaccount = null) {
        $message = null;
        $operateModel = WB_UserTaskOperate::findOne($operateid);
        if (!$operateModel instanceof WB_UserTaskOperate) {
            $message = "您要提交的任务不存在！";
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            foreach ($img as $task_image) {
                $operateModel->task_image = $operateModel->task_image . "," . MTools::upQiniu($task_image, true);
            }
            $operateModel->task_image = trim($operateModel->task_image, ",");
            $operateModel->status = 1;
            $operateModel->uped_at = time();
            $operateModel->upip = Yii::$app->api->realIp();
            $operateModel->is_broker = 1;
            $taskaccount ? $operateModel->taskaccount = $taskaccount : null;
            $result = MTools::saveModel($operateModel);
            if ($result !== true) {
                $message = "提交任务失败";
            } else {
                //返还佣金
                if (WB_UserPayRecordHy::createRecord($operateModel->userid, $operateModel->price, 1, 1, null, $operateModel->id) && $this->checkTaskcomcount($operateModel->taskid)) {
                    $trans->commit();
                    $message = "亲，任务已提交成功！想要赚取更多外快，再去接新任务吧！";
                } else {
                    $message = "提交任务失败";
                }
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            $message = "提交任务失败";
        }
        return $message;
    }

    /*
     * 注册
     */

    public function addRegisterEvent() {
        $model = ArrayHelper::getValue($this->data, "model");
        //验证表单数据
        if (!$model->validate()) {
            $this->errorMessage($model->errors);
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            $user = new \common\models\User();
            $user->username = $model->username;
            $user->role = 2;
            $user->my_code = MTools::makeOnlyNumber();
            $user->setPassword($model->password);
            $user->generateAuthKey();
            $user->generatePasswordResetToken();
            if ($user->save()) {
                //保存基本信息
                $res = WB_UserProfile::find()->where("userid=" . $user->id)->one();
                $userprofile = $res instanceof WB_UserProfile ? $res : new WB_UserProfile();
                $userprofile->userid = $user->id;
                $userprofile->username = $model->username;
                $userprofile->invite_code = $model->invite_code;
                $userprofile->truename = $model->truename;
                $userprofile->alipay = $model->alipay;
                $userprofile->qq = $model->qq;
                $this->data["userid"] = $user->id;
                if ($userprofile->save() && $this->updateAmount() && Yii::$app->getUser()->login($user)) {
                    $trans->commit();
                    $this->sender->flag = 1;
                    $this->sender->message = "注册成功";
                } else {
                    $this->sender->message = "注册失败";
                }
            } else {
                $this->sender->message = "注册失败";
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

    /*
     * 刷新任务列表事件
     */

    public function reflashTasklist() {
        $this->monitorTop();
        $this->monitorReflash();
    }

    /*
     * 做过的任务刷新
     */

    public function myOperateList() {
        $time = time();
        WB_UserTaskOperate::deleteAll("status = 0 and created_at <=" . ($time - 600));
    }

    /*
     * 申诉任务
     */

    public function appealTask() {
        $operateModel = WB_UserTaskOperate::findOne(ArrayHelper::getValue($this->data, "operateid"));
        if (!$operateModel instanceof WB_UserTaskOperate) {
            $this->sender->message = "获取任务延迟，请稍后重试";
            return false;
        }
        $now = time();
        if ($now - $operateModel->updated_at >= 86400 * 3) {
            $this->sender->message = "任务投诉成功已超过3天，就不能申诉任务了";
            return false;
        }
        $task_imagearr = UploadedFile::getInstances($operateModel, "task_image[]");
        if (!$task_imagearr) {
            $this->sender->message = "请上传图片";
            return false;
        }
        $this->_task = WB_Task::findOne($operateModel->taskid);
        $imagecount = count($task_imagearr);
        if ($imagecount > $this->_task->sample_figure_count) {
            $this->sender->message = "当前任务只允许上次【" . $this->_task->sample_figure_count . "张】样图，您上传了【" . $imagecount . "张】";
            return false;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            foreach ($task_imagearr as $task_image) {
                $operateModel->appeal_task_image = $operateModel->appeal_task_image . "," . MTools::upQiniu($task_image->tempName);
            }
            $operateModel->appeal_task_image = trim($operateModel->appeal_task_image, ",");
            $operateModel->appeal_at = time();
            $operateModel->is_complain = 4;
            $operateModel->appeal_taskcount = Yii::$app->request->post("taskaccount");
            $result = MTools::saveModel($operateModel);
            if ($result !== true) {
                $this->errorMessage(ArrayHelper::getValue($result, "errors"));
                return false;
            } else {
                $trans->commit();
                $this->operateSuccess();
            }
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException($ex);
        }
    }

}
